package model

import (
	"encoding/base64"
	"gitee.com/buddyxiao/ginblog/utils/errmsg"
	"golang.org/x/crypto/scrypt"
	"gorm.io/gorm"
	"log"
)

type User struct {
	gorm.Model
	Username string `json:"username" gorm:"type:varchar(20);not null" validate:"required,min=4,max=12" label:"用户名"`
	Password string `json:"password" gorm:"type:varchar(20);not null" validate:"required,min=6,max=20" label:"密码"`
	Role     int    `json:"role" gorm:"type:tinyint;default:2" validate:"required,gte=2" label:"角色"`
}

// CheckUser 查询用户是否存在
func CheckUser(username string) (code int) {
	var users User
	db.Select("id").Where("username = ?", username).First(&users)
	if users.ID > 0 {
		code = errmsg.ERROR_USERNAME_USED // 用户已存在
	} else {
		code = errmsg.SUCCESS // 用户不存在
	}
	return
}

// CheckUpUser 更新查询
func CheckUpUser(id int, username string) (code int) {
	var users User
	db.Select("id").Where("username = ?", username).Find(&users)
	if users.ID == uint(id) {
		code = errmsg.SUCCESS // 用户名不存在
	} else {
		code = errmsg.ERROR_USERNAME_USED // 用户名已存在
	}
	return
}

// CreateUser 新增用户
func CreateUser(data *User) (code int) {

	data.Password = scryptPw(data.Password)
	if db.Create(data).Error != nil {
		code = errmsg.ERROR
		return
	}
	code = errmsg.SUCCESS
	return
}

// GetUser 查询某个用户
func GetUser(id int) (User, int) {
	var user User
	if db.First(&user, id).Error != nil {
		return user, errmsg.ERROR
	}
	return user, errmsg.SUCCESS
}

// GetUsers 查询用户列表
func GetUsers(username string, pageNum int, pageSize int) ([]User, error, int) {
	// 查询第几页的所有数据
	offsetValue := (pageNum - 1) * pageSize
	if pageNum == -1 {
		offsetValue = -1 // 不做分页处理
	}
	var users []User
	var total int64
	if username == "" {
		// 求总数
		db.Model(&User{}).Count(&total)
		err = db.Limit(pageSize).Offset(offsetValue).Find(&users).Error
		if err != nil {
			return nil, err, 0
		}
		return users, nil, int(total)
	}
	db.Model(&User{}).Where("username like concat('%',?,'%')", username).Count(&total)
	err = db.Limit(pageSize).Offset(offsetValue).Where("username like concat('%',?,'%')", username).Find(&users).Error
	if err != nil {
		return nil, err, 0
	}
	return users, nil, int(total)
}

// DeleteUser 删除用户
func DeleteUser(id int) int {
	if db.Delete(&User{}, id).Error != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// EditUser 编辑用户
func EditUser(id int, data *User) int {
	var maps = make(map[string]interface{})
	maps["username"] = data.Username
	maps["role"] = data.Role
	if db.Model(&User{}).Where("id=?", id).Updates(maps).Error != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 密码加密
func scryptPw(password string) string {
	const KeyLen = 10
	salt := []byte{12, 34, 4, 6, 66, 22, 222, 11}
	HashPw, err := scrypt.Key([]byte(password), salt, 32768, 8, 1, KeyLen)
	if err != nil {
		log.Fatal(err)
	}
	encodedPw := base64.StdEncoding.EncodeToString(HashPw)
	return encodedPw
}

// CheckLogin 登录验证
func CheckLogin(username string, password string) int {
	var user User
	db.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		return errmsg.ERROR_USER_NOT_EXIST
	}
	if scryptPw(password) != user.Password {
		return errmsg.ERROR_PASSWORD_WRONG
	}
	if user.Role != 1 {
		return errmsg.ERROR_USER_NO_RIGHT
	}
	return errmsg.SUCCESS
}
